package csd.wyaiyr.com.config;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public abstract class BaseServiceImpl<T> implements BaseService<T> {


    @Autowired
    protected IBaseMapper<T> mapper;

    // 批量操作
    public int saveBatch(List<T> recordList) {
        return mapper.insertList(recordList);
    }

    public int deleteByPK(Object key) {
        return mapper.deleteByPrimaryKey(key);
    }

    public int deleteByIds(String ids) {
        return mapper.deleteByIds(ids);
    }

//   根据主键更新实体全部字段，null值会被更新

    public int updateByPK(T record) {
        return mapper.updateByPrimaryKey(record);
    }

    public T getOneByPK(Object key) {
        return mapper.selectByPrimaryKey(key);
    }

    public T getOneByEntity(T record) {
        return mapper.selectOne(record);
    }

    public List<T> listAll() {
        return mapper.selectAll();
    }

    public List<T> listByIds(String ids) {
        return mapper.selectByIds(ids);
    }

    public int getCount(T record) {
        return mapper.selectCount(record);
    }

    public List<T> listByEntity(T record) {
        return mapper.select(record);
    }

    @Override
    public T selectByKey(Object key) {

        return mapper.selectByPrimaryKey(key);
    }

    @Override
    public int save(T entity) {
        return mapper.insert(entity);
    }

    @Override
    public int updateAll(T entity) {
        return mapper.updateByPrimaryKey(entity);
    }

    @Override
    public int updateNotNull(T entity) {
        return mapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public int saveSelective(T entity) {
        return mapper.insertSelective(entity);
    }

    public PageInfoResult getPage(List<?> list, QueryPage query) {

        PageInfoResult page = new PageInfoResult();
        long pages = ((Page<?>) list).getPages();
        page.setPages(pages);
        page.setTotal(((Page<?>) list).getTotal());
        page.setPageSize(query.getPageSize());
        page.setPageNum(query.getPageNum());
        return page;
    }

    public PageInfoResult getPage(List<?> list, int pageNum, int pageSize) {

        PageInfoResult page = new PageInfoResult();
        long pages = ((Page<?>) list).getPages();
        page.setPages(pages);
        page.setTotal(((Page<?>) list).getTotal());
        page.setPageSize(pageSize);
        page.setPageNum(pageNum);
        return page;

    }

    @Override
    public PageInfo<T> selectListPage(Integer pageNo, Integer pageSize, T t) {
        PageHelper.startPage(pageNo.intValue(), pageSize.intValue());
        List<T> list = this.mapper.select(t);
        return new PageInfo(list);
    }

}
